import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {mobileValidator, qrcodeValidator} from '../../common/validators';
import {Events, LoadingController, NavController, ToastController} from '@ionic/angular';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {HttpService} from '../../services/http.service';
import {KeyAndSign} from '../../common/key-and-sign.enum';
import {AppConfig} from '../../common/app-config.enum';
import {UtilService} from '../../services/util.service';
import {Logout} from '../../actions/auth.actions';
import {AuthState} from '../../reducers/auth.reducer';
import {Store} from '@ngrx/store';
import {Storage} from '@ionic/storage';
import {mergeMap} from 'rxjs/internal/operators';
import {fromPromise} from 'rxjs/internal/observable/fromPromise';
import {Observable, of} from 'rxjs';

/**
 * 修改密码
 */
@Component({
  selector: 'app-retrieve-password',
  templateUrl: './retrieve-password.page.html',
  styleUrls: ['./retrieve-password.page.scss'],
})
export class RetrievePasswordPage extends BasePage implements OnInit {

  public formModel: FormGroup;
  public pwdObj: any = {
    inputType: 'password',
    icon: 'md-eye-off',
    color: 'medium'
  };
  public resendTime = 0;
  public isLogout = true;

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private loadingCtrl: LoadingController,
              private fb: FormBuilder,
              private service$: HttpService,
              private utilService: UtilService,
              private store: Store<AuthState>,
              private events: Events,
              private storage: Storage
  ) {
    super(navCtrl, toastCtrl);
    this.formModel = this.fb.group({
      mobile: [null, [Validators.required, mobileValidator]],
      smsCodeSign: [null, [Validators.required, qrcodeValidator]],
      newPassword: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
      userType: [1, [Validators.required]],
      scene: ['forgetPwd']
    });
  }

  ngOnInit() {
    // 读取本地用户信息，如果已登录，设置手机号码并禁止修改
    this.storage.get(AppConfig.USER_INFO)
      .then(userInfo => {
        if (userInfo && userInfo['mobile']) {
          this.formModel.get('mobile').setValue(userInfo['mobile']);
          this.isLogout = false;
        }
      });
  }

  // 执行重置密码
  async doRetrieve() {
    if (this.formModel.valid) {
      const loading = await this.loadingCtrl.create({
        message: '密码重置中'
      });
      loading.present();
      // 对password加密
      const newPassword = this.utilService.encryptByDES(this.formModel.get('newPassword').value, KeyAndSign.DES_KEY);
      const smsCodeSign = this.utilService.encryptByDES(this.formModel.get('smsCodeSign').value, KeyAndSign.DES_KEY);
      this.service$.doRequest(UrlAndOPT.auth_retrievePassword, {
        ...this.formModel.value,
        newPassword: newPassword,
        smsCodeSign: smsCodeSign
      })
        .pipe(
          mergeMap(obj => {
            if (obj) { // 重置密码成功
              return fromPromise(this.storage.get(AppConfig.USER_INFO)) // 判断是否是登录状态
                .pipe(
                  mergeMap(userInfo => {
                    if (userInfo) { // 如果为登录状态执行退出
                      return this.doLogout();
                    }
                    return of(true);
                  })
                );
            }
            return of(false);
          })
        )
        .subscribe(async obj => {
          await loading.dismiss();
          if (obj) {
            // 发送手机号
            this.events.publish(AppConfig.TOPIC_MOBILE, {mobile: this.formModel.get('mobile').value});
            // 清除本地用户信息
            await this.service$.clearUserInfo();
            // 发送退出状态
            this.store.dispatch(new Logout({status: 0, userInfo: {}, response: null}));
            // 显示通知，跳转至登录页
            await this.showToast('已重置密码，请重新登录');
            this.formModel.patchValue({
              mobile: null,
              smsCodeSign: null,
              newPassword: '',
              userType: 1,
              scene: 'forgetPwd'
            });
            await this.navCtrl.pop();
            await this.navCtrl.navigateForward(['/login']);
          }
        });
    } else {
      await this.showToast('请完善信息');
    }
  }

  // 发送验证码
  getVCode() {
    // 需要scene参数： register：注册时；forgetPwd：忘记密码时
    // 发送验证码时会自动校验手机号是否重复
    if (this.formModel.get('mobile').valid) {
      this.service$.doRequest(UrlAndOPT.auth_getScene, {
        mobile: this.formModel.get('mobile').value,
        scene: this.formModel.get('scene').value
      })
        .subscribe(obj => {
          if (obj) {
            this.showToast(obj['msg']).catch(() => {
            });
            this.resendTime = AppConfig.RESEND_TIME; // 下次发送时间间隔
            const timer = setInterval(() => {
              this.resendTime--;
              if (this.resendTime === 0) {
                clearInterval(timer);
              }
            }, 1000);
          }
        });
    } else {
      this.showToast('手机号有误，请重新输入');
    }
  }

  // 执行退出登录 userId  deviceType
  private doLogout(): Observable<any> {
    return fromPromise(this.storage.get(AppConfig.USER_PLATFORM))
      .pipe(
        mergeMap(deviceType => {
          return this.service$.doRequest(UrlAndOPT.auth_logout, {deviceType: deviceType});
        })
      );
  }

  // 切换显示密码
  showPassword() {
    const isText = this.pwdObj.inputType === 'text';
    this.pwdObj = {
      inputType: isText ? 'password' : 'text',
      icon: isText ? 'md-eye-off' : 'md-eye',
      color: isText ? 'medium' : 'tertiary'
    };
  }

}
